
accessid = ''
accesskey = ''
host = ''
policyBase64 = ''
signature = ''
callbackbody = ''
filename = ''
key = ''
expire = 0
g_object_name = ''
g_object_name_type = ''
imgstr=''
delImgStr=''
now = timestamp = Date.parse(new Date()) / 1000;
    function send_request() {
        var xmlhttp = null;
        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        key='dingyuan/activity2018/'+$("#orgId").val()+'/'
        if (xmlhttp != null) {
            serverUrl = '/marketing/ossSignature?dir='+key;
            xmlhttp.open("GET", serverUrl, false);
            xmlhttp.send(null);
            return xmlhttp.responseText
        } else {
            alert("Your browser does not support XMLHTTP.");
        }
    };

    // function check_object_radio() {
    //     var tt = document.getElementsByName('myradio');
    //     for (var i = 0; i < tt.length; i++) {
    //         if (tt[i].checked) {
    //             g_object_name_type = tt[i].value;
    //             break;
    //         }
    //     }
    // }

    function get_signature() {
        //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
        now = timestamp = Date.parse(new Date()) / 1000;
        if (expire < now + 60*50) {
            body = send_request()
            var obj = eval("(" + body + ")");
            console.log(obj)
            host = obj['host']
            policyBase64 = obj['policy']
            accessid = obj['accessid']
            signature = obj['signature']
            expire = parseInt(obj['expire'])
            callbackbody = obj['callback']
            key = obj['dir']
            return true;
        }
        return false;
    };

    function random_string(len) {
        len = len || 32;
        var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        var maxPos = chars.length;
        var pwd = '';
        for (i = 0; i < len; i++) {
            pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }

    //获取后缀
    function get_suffix(file) {
        console.log("****************")
        console.log(file.name)
        pos = file.name.lastIndexOf('.')
        suffix = ''
        if (pos != -1) {
            suffix = file.name.substring(pos)
        }
        return suffix;
    }
    function get_uploaded_object_name(file) {
        suffix = get_suffix(file);
        console.log(suffix)
        g_object_name = file.id+suffix
        console.log(g_object_name)
        return g_object_name
    }

    function set_upload_param(up, file, ret) {
        console.log(up.files)
        if (ret == false) {
            ret = get_signature()
        }
        //g_object_name = key;
        if (file != '') {
            get_uploaded_object_name(file)
        }
        new_multipart_params = {
            'key': key+g_object_name,
            'policy': policyBase64,
            'OSSAccessKeyId': accessid,
            'success_action_status': '200', //让服务端返回200,不然，默认会返回204
            'callback': callbackbody,
            'signature': signature,
        };

        up.setOption({
            'url': host,
            'multipart_params': new_multipart_params
        });

        up.start();
    }

    function previewImage(file, callback) {
        if (file.type == 'image/gif') {
            var fr = new mOxie.FileReader();
            fr.onload = function () {
                callback(fr.result);
                fr.destroy();
                fr = null;
            }
            fr.readAsDataURL(file.getSource());
        } else {
            var preloader = new mOxie.Image();
            preloader.onload = function () {
                var imgsrc = preloader.type == 'image/jpeg' ? preloader.getAsDataURL('image/jpeg', 80) : preloader.getAsDataURL();
                callback && callback(imgsrc);
                preloader.destroy();
                preloader = null;
            };
            preloader.load(file.getSource());
        }
    }
        var uploader = new plupload.Uploader({
            runtimes: 'html5,flash,silverlight,html4',
            browse_button: 'getfiles',
            //multi_selection: false,
            container: document.getElementById('container'),
            flash_swf_url: '../lib/plupload-2.1.2/js/Moxie.swf',
            silverlight_xap_url: '../lib/plupload-2.1.2/js/Moxie.xap',
            url: 'http://oss.aliyuncs.com',
            filters: {
                mime_types: [ //只允许上传图片文件
                    {
                        title: "Image files",
                        extensions: "jpg,gif,png,bmp"
                    }
                ],
                max_file_size: '3mb', //最大只能上传3mb的文件
                prevent_duplicates: false //不允许选取重复文件
            },

            init: {
                PostInit: function () {
                    imgstr='';
                    document.getElementById('ossfile').innerHTML = '';
                    document.getElementById('postfiles').onclick = function () {
                        set_upload_param(uploader, '', false);
                        return false;
                    };
                },

                FilesAdded: function (up, files) {
                    console.log(files)
                    plupload.each(files, function (file) {
                        // document.getElementById('ossfile').innerHTML += '<div  class=file_name id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>' +
                        //     '<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>' +
                        //     '</div>';
                        //显示预览图片
                        previewImage(file, function(imgSrc) {
                            var domstr = '<div class="imgBox"><div  class=file_name id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>'+
                                '<div class="progress"><div class="progress-bar" style="width: 0%"></div></div></div>' +
                                '<img src=' + imgSrc + ' /><button id=' + get_uploaded_object_name(file) + ' class="layui-btn layui-btn-danger delete_btn">删除</button></div>'
                            $('#cardFrontImg').append(domstr)
                        });
                    });

                },

                BeforeUpload: function (up, file) {
                    set_upload_param(up, file, true);
                },

                UploadProgress: function (up, file) {
                    var d = document.getElementById(file.id);
                    d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
                    var prog = d.getElementsByTagName('div')[0];
                    var progBar = prog.getElementsByTagName('div')[0]
                    progBar.style.width = 3 * file.percent + 'px';
                    progBar.setAttribute('aria-valuenow', file.percent);
                },

                FileUploaded: function (up, file, info) {

                    if (info.status == 200) {
                        document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '图片上传成功, 文件名:' + get_uploaded_object_name(file);

                        if(imgstr) {
                            imgstr +=  get_uploaded_object_name(file)+"SPLIT"
                        } else {
                            imgstr = get_uploaded_object_name(file)+"SPLIT";
                        }
                        // var imgstrAA="asdfs2342fsadfasdfasefsaasdfs2342fsadfasdfasefsa";
                        // console.log("@@@"+imgstr);
                        $.cookie('imgStr',imgstr);
                        //console.log("66666666666");
                    } else {
                        document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
                    }

                },

                Error: function (up, err) {
                    if (err.code == -600) {
                        layer.msg("选择的图片太大了");
                        //document.getElementById('console').appendChild(document.createTextNode("\n选择的文件太大了,可以根据应用情况，在upload.js 设置一下上传的最大大小"));
                    } else if (err.code == -601) {
                        layer.msg("请选择正确格式的图片");
                        //document.getElementById('console').appendChild(document.createTextNode("\n选择的文件后缀不对,可以根据应用情况，在upload.js进行设置可允许的上传文件类型"));
                    } else if (err.code == -602) {
                        layer.msg("这个文件已经上传过一遍了");
                        //document.getElementById('console').appendChild(document.createTextNode("\n这个文件已经上传过一遍了"));
                    } else {
                        layer.msg(err.response);
                        //document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
                    }
                }
            }
        });

        uploader.init();

/*删除图片*/
$('#cardFrontImg').on('click', '.delete_btn', function() {
    var files = uploader.files;
    var id = $(this).attr('id');
    console.log("*****************************");
    console.log(id);
    for(var i = 0; i < files.length; i++) {
        var filename = get_uploaded_object_name(files[i])
        if( filename == id) {
            console.log("+++++++++++++++++++++++++++");
            console.log(filename);
            imgstr=imgstr.replace(filename+"SPLIT","");
            console.log(imgstr);
            $.cookie('imgStr',null);
            $.cookie('imgStr',imgstr);
            //delImgs(filename,$("#orgId").val(),uploader,this);//与后台交互，删除图片


            $.ajax({
                url:'/marketing/delImgs',
                type:'POST', //GET
                async:true,    //或false,是否异步
                data:{
                    id:filename,
                    orgId:$("#orgId").val()
                },
                timeout:5000,    //超时时间
                dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
                beforeSend:function(xhr){
                    /*console.log(xhr)
                     console.log('发送前')*/
                },
                success:function(data){
                    console.log(data);
                    if (data.code='000000'){

                    }else {
                        layer.msg("删除失败");
                    }
                },
                error:function(xhr,textStatus){
                    console.log('错误')
                    console.log(xhr)
                    console.log(textStatus)
                },
                complete:function(){
                    //console.log('结束')
                }
            });

            uploader.removeFile(files[i]);
            $(this).parent('.imgBox').remove();
        }
    }
})

